/*
 * @Author: WangShuai 1830773767@qq.com
 * @Date: 2023-12-12 22:45:29
 * @LastEditors: WangShuai 1830773767@qq.com
 * @LastEditTime: 2025-06-12 22:30:04
 * @FilePath: \vue3_admin_template\project\src\store\modules\user.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
//创建用户小仓库
import { defineStore } from 'pinia'
//引入用户登录接口
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user/index.ts'
//引入类型
import type {
  loginFormData,
  loginResponseData,
  userInfoResponseData,
  logoutResponseData,
} from '@/api/user/type.ts'
import type { UserState } from './type/types'
//引入本地存储token的公共方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
//引入constantRoute常量路由
import { constantRoute, asyncRoute, anyRoute } from '@/router/routers'
import router from '@/router'
//引入深拷贝
//@ts-ignore  忽略ts检查
import cloneDeep from 'lodash/cloneDeep.js'
//根据不同用户的路由信息过滤异步路由
function filterRoutes(asyncRouter: any, routers: any) {
  return asyncRouter.filter((item: any) => {
    if (routers.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterRoutes(item.children, routers)
      }
      return true
    }
  })
}
//声明一个小仓库
let useUserStore = defineStore('user', {
  //小仓库存储数据的地方
  state: (): UserState => {
    return {
      // token: localStorage.getItem('TOKEN'), //用户唯一标识token
      token: GET_TOKEN(), //用户唯一标识token
      menuRoutes: constantRoute, //仓库存储菜单需要的数组(路由)
      username: '',
      avatar: '',
      buttons: [], //存储用户是否包含某一个按钮的数组
    }
  },
  //异步|处理逻辑的地方
  actions: {
    //处理用户登录的方法
    async userLogin(data: loginFormData) {
      //登录请求
      let result: loginResponseData = await reqLogin(data)
      // 返回数据格式
      //  result={
      //     code: 200,
      //     data: "fjdskggsggkljsdfjkgjihgdifasdjjdnsdjhd",
      //     message:"登录成功",
      //     success: true,
      // }
      //登录请求:成功200=>token
      //登录请求失败201-->登录失败错误信息
      // console.log('登录请求', result)
      if (result.code == 200) {
        //pinia仓库存储一下token
        //由于pinia|vuex存储数据其实是利用js对象
        this.token = result.data as string
        // this.token = result.data as string
        //本地持久化存储
        // localStorage.setItem('TOKEN', (result.data.token as string))
        // SET_TOKEN(result.data as string)
        SET_TOKEN(result.data as string)
        return 'ok'
      } else {
        // return Promise.reject(new Error(result.data))
        return Promise.reject(new Error(result.data))
      }
    },
    //获取用户信息
    async userInfo() {
      //获取用户信息进行存储仓库当中[头像,名字]
      let result: userInfoResponseData = await reqUserInfo()
      //如果 获取用户信息成功,存储一下用户信息
      if (result.code == 200) {
        //console.log("this指向",this)//this指的是当前 Pinia store 的实例。具体而言，它代表着由defineStore函数所创建的user store 实例。
        ;(this.username = result.data.name), (this.avatar = result.data.avatar)
        // this.username = result.data.
        // this.avatar = result.data.avatar
        this.buttons = result.data.buttons
        //计算当前用户需要的 异步路由
        let userAsyncRoute = filterRoutes(
          cloneDeep(asyncRoute),
          result.data.routes,
        )
        //菜单需要的数据 整理完毕
        this.menuRoutes = [...constantRoute, ...userAsyncRoute, anyRoute]
        //目前路由器所管理的路由只有常量路由,用户计算的异步路由和任意路由动态追加
        let userAsyncRouteNew = [...userAsyncRoute, anyRoute]
        userAsyncRouteNew.forEach((route: any) => {
          router.addRoute(route)
        })
        // console.log("object", this.menuRoutes);
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },

    //退出登录接口
    async userLogout() {
      //调用退出登录的接口
      let result: logoutResponseData = await reqLogout()
      //如果退出登录成功
      if (result.code == 200) {
        //清除仓库中用户相关的数据
        this.token = ''
        this.username = ''
        this.avatar = ''
        this.menuRoutes = []
        //清除本地存储的token
        REMOVE_TOKEN()
        return Promise.resolve(result)
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
  },
  getters: {},
})
//对外暴露user小仓库
export default useUserStore
